package com.judian.smart.util;


import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Environment;
import android.util.Log;

import com.tencent.bugly.crashreport.CrashReport;
import com.judian.smart.activity.MainActivity;
import com.judian.smart.base.MyApplication;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.Thread.UncaughtExceptionHandler;

/**
 * 崩溃日志收集器。
 *
 * @author <a href="http://www.xfyun.cn">讯飞开放平台</a>
 * @date 2016年6月27日 下午7:48:02
 */
public class CrashCollector implements UncaughtExceptionHandler {
    private static final String TAG = "CrashCollector";

    private static final String CRASH_LOG_DIR = Environment.getExternalStorageDirectory().getAbsolutePath()
            + "/ZunderHome/crash/";

    private UncaughtExceptionHandler mDefaultHandler;

    private static CrashCollector INSTANCE = new CrashCollector();

    private FileUtil.DataFileHelper mCrashLogHelper;

    private Context mContext;

    private SharedPreferences mSharedPreferences;
    private SharedPreferences.Editor mEditor;
    private int count = 0;

    private CrashCollector() {

    }

    public static CrashCollector getInstance() {
        return INSTANCE;
    }

    public void init(Context context) {
        mContext = context;
        mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(CrashCollector.this);
        mCrashLogHelper = FileUtil.createFileHelper(CRASH_LOG_DIR);
        mSharedPreferences = MyApplication.getInstance().getSharedPreferences("error_count", Context.MODE_PRIVATE);
        mEditor = mSharedPreferences.edit();
        mEditor.apply();
    }

    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        if (!saveCrashLog(ex) && null != mDefaultHandler) {
            mDefaultHandler.uncaughtException(thread, ex);
        } else {
            int errorCount = mSharedPreferences.getInt("errorCount", 0);
            long errorTime = mSharedPreferences.getLong("errorTime", 0);
            if (errorTime == 0) {
                mEditor.putLong("errorTime", System.currentTimeMillis());
            } else {
                if ((System.currentTimeMillis() - errorTime) > 60000) {
                    mEditor.putInt("errorCount", 0);
                    mEditor.putLong("errorTime", System.currentTimeMillis());
                    Log.d(TAG, "init: !!!!!!!!!!!!!!!!!!!!!!!!!!!!");
                }
            }
            Log.d(TAG, "uncaughtException: 时间 " + (System.currentTimeMillis() - errorTime));
            if (errorCount >= 5 && (System.currentTimeMillis() - errorTime) < 60000) {
                count = 0;
                mEditor.putInt("errorCount", 0);
                mEditor.putLong("errorTime", System.currentTimeMillis());
                mEditor.apply();
                android.os.Process.killProcess(android.os.Process.myPid());
            } else {
                Intent intent = new Intent(mContext,MainActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                mContext.startActivity(intent);
                mEditor.putInt("errorCount", ++count);
                mEditor.apply();
            }
/*            // 退出程序
            android.os.Process.killProcess(android.os.Process.myPid());
            System.exit(1);*/
        }
    }

    private boolean saveCrashLog(Throwable ex) {
        if (null == ex) {
            return false;
        }
        CrashReport.postCatchedException(ex); //手动上传bugly
        Writer writer = new StringWriter();
        PrintWriter printWriter = new PrintWriter(writer);
        ex.printStackTrace(printWriter);
        Throwable cause = ex.getCause();
        while (null != cause) {
            cause.printStackTrace(printWriter);
            cause = cause.getCause();
        }
        String crashLog = writer.toString();
        printWriter.close();
        mCrashLogHelper.createFile("", FileUtil.SURFFIX_TXT, false);
        mCrashLogHelper.write(crashLog.getBytes(), true);
        mCrashLogHelper.closeWriteFile();
        return true;
    }

}

